﻿@using Gurux.DLMS.AMI.Shared.DIs
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Module
@using System.Globalization

@attribute [Authorize(Roles = GXRoles.Admin + "," + GXRoles.Gateway)]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier

@if (Active != null)
{
    <EditForm Model="@Active">
        <DataAnnotationsValidator />
        <GXValidator @ref="_gatewayValidator" OnValidate="OnValidate" />
        <div class="row">
            <div style="width:100%">
                <div class="form-group">
                    <InputNullableSwitch Text="@Properties.Resources.Active" @bind-Value="Active.Active" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Name</label>
                    <InputText id="name" disabled="@IsDeleting" @bind-Value="Active.Name" class="form-control"
                               placeholder=@Properties.Resources.Name />
                    <ValidationMessage For="@(() => Active.Name)" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Description</label>
                    <InputText id="name" disabled="@IsDeleting" class="form-control"
                               @bind-Value="Active.Description" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Identifier</label>
                    <InputText id="name" disabled="@IsDeleting" @bind-Value="Active.Identifier" class="form-control"
                               placeholder=@Properties.Resources.Identifier />
                    <ValidationMessage For="@(() => Active.Identifier)" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Agent</label>
                    <div class="form-control d-inline-flex">
                        <input id="agent" readonly="readonly"
                               value="@Active.Agent?.Name"
                               class="form-control"
                               placeholder=@Properties.Resources.Agent />
                        &nbsp;
                        @if (Active.Agent != null)
                        {
                            <a target="_blank" href="@("Agent/Edit/" + Active.Agent.Id)">
                                @Properties.Resources.Manage
                            </a>
                        }
                    </div>
                </div>
                @if (Active.Detected != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Detected</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" 
                        id="detected" readonly="readonly" class="form-control"
                        @bind-Value="Active.Detected" />
                    </div>
                }
                @if (Active.CreationTime != DateTime.MinValue)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.CreationTime</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" 
                        id="generation" readonly="readonly" class="form-control"
                        @bind-Value="Active.CreationTime" />
                    </div>
                }
                @if (Active.Updated != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Updated</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" 
                        id="updated" readonly="readonly" class="form-control"
                        @bind-Value="Active.Updated" />
                    </div>
                }
                @if (Active.Removed != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Removed</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" 
                        id="removed" class="form-control"
                        @bind-Value="Active.Removed" />
                    </div>
                }
                @if (action == CrudAction.Delete)
                {
                    <hr />
                    <p>
                    </p>
                    <div class="form-group">
                        <InputRadioGroup @bind-Value="DeleteTarget">
                            <InputRadio Value="false">
                            </InputRadio>
                            <label>@Properties.Resources.TargetDisableQuestion</label><br>
                            <InputRadio Value="true">
                            </InputRadio>
                            <label>@Properties.Resources.TargetDeleteQuestion</label>
                        </InputRadioGroup>
                        <br />
                    </div>
                }
            </div>
        </div>
    </EditForm>
}
@code {
    private bool DeleteTarget;
    [CascadingParameter]
    private GatewayTab? Parent { get; set; }

    private GXGateway? _active;

    private GXGateway? Active
    {
        get
        {
            if (Parent?.Active != null)
            {
                return Parent.Active;
            }
            return _active;
        }
    }

    private GXValidator? _gatewayValidator;

    /// <summary>
    /// User action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    private CrudAction action;
    /// <summary>
    /// Selected item.
    /// </summary>
    [Parameter]
    public Guid? Id { get; set; }

    public string? IsDeleting
    {
        get
        {
            if (action != CrudAction.Delete)
            {
                return null;
            }
            return "disabled";
        }
    }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.Clear();
            if (Active == null && Id != null)
            {
                //Get gateway data.
                var tmp = (await Http.GetAsJsonAsync<GetGatewayResponse>(string.Format("api/Gateway?id={0}", Id)));
                if (tmp?.Item != null)
                {
                    _active = tmp.Item;
                }
                else
                {
                    NavigationManager.NavigateTo("404");
                }
            }
            if (Active == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidTarget);
            }
            action = ClientHelpers.GetAction(Action);
            if (action == CrudAction.Delete)
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Remove, Icon = "oi oi-trash", OnClick = OnSave });
            }
            else
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Save, Icon = "oi oi-pencil", OnClick = OnSave });
            }
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Cancel, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Validate the gateway content.
    /// </summary>
    /// <param name="sender"></param>
    private void OnValidate(GXValidator sender)
    {
        if (Active != null)
        {
            if (string.IsNullOrEmpty(Active.Name))
            {
                sender.AddError(() => Active.Name, "Invalid name.");
            }
        }
    }

    /// <summary>
    /// Save Active.
    /// </summary>
    public async void OnSave()
    {
        try
        {
            _gatewayValidator?.ClearErrors();
            if (Active == null)
            {
                throw new Exception(Properties.Resources.InvalidTarget);
            }
            if (_gatewayValidator != null && !_gatewayValidator.Validate())
            {
                return;
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            if (action == CrudAction.Delete)
            {
                await Http.PostAsJson<RemoveGatewayResponse>("api/Gateway/Delete",
                    new RemoveGateway()
                        {
                            Ids = new Guid[] { Active.Id },
                            Delete = DeleteTarget
                        }
                    );
            }
            else
            {
                string address;
                if (action == CrudAction.Create)
                {
                    address = "api/Gateway/Add";
                }
                else if (action == CrudAction.Update)
                {
                    address = "api/Gateway/Update";
                }
                else
                {
                    throw new Exception(Properties.Resources.InvalidTarget);
                }
                await Http.PostAsJson<UpdateGatewayResponse>(address, new UpdateGateway()
                    {
                        Gateways = new GXGateway[] { Active }
                    });
            }
            ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier.ProgressEnd();
            StateHasChanged();
        }
    }

    /// <summary>
    /// Cancel update.
    /// </summary>
    private void OnCancel()
    {
        ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
    }
}